<template>
  <div class="row relative-position">
    <div class="col-5 q-pa-md">
      <q-card class="bg-half-black full-height column" :class="ui.cardClass">
        <div class="col-2 row">
          <q-btn
            label="相机预览"
            class="full-width text-h5"
            :style="ui.isDark ? 'border: 1px solid rgba(255,255,255,0.5)' : ''"
            :loading="isPreview"
            @click="handleCameraPreview"
          >
            <template v-slot:loading>
              <q-spinner-hourglass class="on-left" />
              {{ $t("selfCalibrate.准备中") }}
            </template>
          </q-btn>
        </div>
        <div class="col-10 row">
          <img
            src="/postPure/empty.svg"
            :alt="$t('selfCalibrate.图片')"
            style="width: 100%; height: 100%"
            ref="imgRef"
          />
        </div>
      </q-card>
    </div>
    <div class="col-7 q-pa-md" style="height: 100%">
      <q-card class="bg-half-black full-height column" :class="ui.cardClass">
        <div class="col-2 row">
          <q-btn
            label="获取坐标系"
            class="full-width text-h5"
            :class="ui.isDark ? '' : 'q-mb-sm'"
            :style="ui.isDark ? 'border: 1px solid rgba(255,255,255,0.5)' : ''"
            @click="getCord(true)"
          />
        </div>
        <div class="col-10 row">
          <div class="col">
            <q-btn
              label="获取左夹具"
              class="full-width text-subtitle1"
              style="height: 20%"
              @click="getPosture(true, 'flange')"
            />
            <q-scroll-area class="q-pa-sm" style="height: 65%">
              <div class="q-gutter-y-sm">
                <q-item-label class="text-subtitle1">位置信息</q-item-label>
                <div class="row q-gutter-x-sm">
                  <q-input
                    :dark="ui.isDark"
                    dense
                    outlined
                    type="tel"
                    v-model.number="leftPosture.pose.position.x"
                    class="col"
                    label="X"
                  />
                  <q-input
                    :dark="ui.isDark"
                    dense
                    outlined
                    type="tel"
                    v-model.number="leftPosture.pose.position.y"
                    class="col"
                    label="Y"
                  />
                </div>
                <q-input
                  :dark="ui.isDark"
                  dense
                  outlined
                  type="tel"
                  v-model.number="leftPosture.pose.position.z"
                  class="col"
                  label="Z"
                />
                <q-separator />
                <q-item-label class="text-subtitle1">角度信息</q-item-label>
                <div class="row q-gutter-x-sm">
                  <q-input
                    :dark="ui.isDark"
                    dense
                    outlined
                    type="tel"
                    v-model.number="leftPosture.pose.orientation.x"
                    class="col"
                    label="X"
                  />
                  <q-input
                    :dark="ui.isDark"
                    dense
                    outlined
                    type="tel"
                    v-model.number="leftPosture.pose.orientation.y"
                    class="col"
                    label="Y"
                  />
                </div>
                <div class="row q-gutter-x-sm">
                  <q-input
                    :dark="ui.isDark"
                    dense
                    outlined
                    type="tel"
                    v-model.number="leftPosture.pose.orientation.z"
                    class="col"
                    label="Z"
                  />
                  <q-input
                    :dark="ui.isDark"
                    dense
                    outlined
                    type="tel"
                    v-model.number="leftPosture.pose.orientation.w"
                    class="col"
                    label="W"
                  />
                </div>
              </div>
            </q-scroll-area>
            <div class="q-pa-sm" style="height: 15%">
              <q-btn
                label="保存左夹具"
                class="full-width"
                :style="ui.isDark ? 'border: 1px solid white' : ''"
                @click="save('left')"
              />
            </div>
          </div>
          <div
            class="col"
            :style="
              ui.isDark
                ? 'border-left: 1px solid rgba(255,255,255,0.5);height: 100%'
                : ''
            "
          >
            <q-btn
              label="获取右夹具"
              class="full-width text-subtitle1"
              style="height: 20%"
              @click="getPosture(true, 'tool_2')"
            />
            <q-scroll-area class="q-pa-sm" style="height: 65%">
              <div class="q-gutter-y-sm">
                <q-item-label class="text-subtitle1">位置信息</q-item-label>
                <div class="row q-gutter-x-sm">
                  <q-input
                    :dark="ui.isDark"
                    dense
                    outlined
                    type="tel"
                    v-model.number="rightPosture.pose.position.x"
                    class="col"
                    label="X"
                  />
                  <q-input
                    :dark="ui.isDark"
                    dense
                    outlined
                    type="tel"
                    v-model.number="rightPosture.pose.position.y"
                    class="col"
                    label="Y"
                  />
                </div>
                <q-input
                  :dark="ui.isDark"
                  dense
                  outlined
                  type="tel"
                  v-model.number="rightPosture.pose.position.z"
                  class="col"
                  label="Z"
                />
                <q-separator />
                <q-item-label class="text-subtitle1">角度信息</q-item-label>
                <div class="row q-gutter-x-sm">
                  <q-input
                    :dark="ui.isDark"
                    dense
                    outlined
                    type="tel"
                    v-model.number="rightPosture.pose.orientation.x"
                    class="col"
                    label="X"
                  />
                  <q-input
                    :dark="ui.isDark"
                    dense
                    outlined
                    type="tel"
                    v-model.number="rightPosture.pose.orientation.y"
                    class="col"
                    label="Y"
                  />
                </div>
                <div class="row q-gutter-x-sm">
                  <q-input
                    :dark="ui.isDark"
                    dense
                    outlined
                    type="tel"
                    v-model.number="rightPosture.pose.orientation.z"
                    class="col"
                    label="Z"
                  />
                  <q-input
                    :dark="ui.isDark"
                    dense
                    outlined
                    type="tel"
                    v-model.number="rightPosture.pose.orientation.w"
                    class="col"
                    label="W"
                  />
                </div>
              </div>
            </q-scroll-area>
            <div class="q-pa-sm" style="height: 15%">
              <q-btn
                label="保存右夹具"
                class="full-width"
                :style="ui.isDark ? 'border: 1px solid white' : ''"
                @click="save('right')"
              />
            </div>
          </div>
        </div>
      </q-card>
    </div>
    <q-inner-loading
      :showing="loading"
      :label="$t('routeManage.PosturePoint.获取当前姿态')"
      label-class="text-teal"
      label-style="font-size: 1.1rem"
    />
  </div>
</template>
<script setup>
import { useUiStore } from "stores/ui";
import { ref, onMounted, onBeforeMount } from "vue";
import { useQuasar } from "quasar";
import { useAPIStore } from "stores/api";
import { api } from "boot/axios";
import { v4 as uuidv4 } from "uuid";
import { useI18n } from "vue-i18n";

const t = useI18n().t;
const lang = "StorageManage.ModifyStorage.";
const ui = useUiStore();
const $q = useQuasar();
const posture = ref({
  parent: "flange",
  child: "",
  pose: {
    orientation: {
      x: "",
      y: "",
      z: "",
      w: "",
    },
    position: {
      x: "",
      y: "",
      z: "",
    },
  },
}); // 当前姿态点信息
const isPreview = ref(false);
const loading = ref(false);
const imgRef = ref();
const frameOptions = ref([]);
const leftPosture = ref({
  parent: "flange",
  child: "",
  pose: {
    orientation: {
      x: "",
      y: "",
      z: "",
      w: "",
    },
    position: {
      x: "",
      y: "",
      z: "",
    },
  },
});
const rightPosture = ref({
  parent: "flange",
  child: "",
  pose: {
    orientation: {
      x: "",
      y: "",
      z: "",
      w: "",
    },
    position: {
      x: "",
      y: "",
      z: "",
    },
  },
});

onBeforeMount(() => {});

onMounted(() => {
  getFrameList();
  getPosture(false, "flange");
  getPosture(false, "flange");
});

// 获取所有坐标系
function getFrameList() {
  api
    .post(
      useAPIStore().amrUrl + "ros/call",
      {},
      { params: { service: "tf/list_frames" } }
    )
    .then((res) => {
      frameOptions.value = res.data.values.frames;
      // 判断除自身库外进行筛选
      const isExist =
        frameOptions.value.filter((item) => item === "platform").length === 0;
      if (isExist) {
        $q.dialog({
          dark: ui.isDark,
          title: t(lang + "当前坐标系丢失"),
          message: t(lang + "获取规格内校准坐标系需移动到拍照点进行获取"),
          html: true,
          cancel: t("cancel"),
          ok: t(lang + "获取"),
        }).onOk(() => {
          getCord(false);
        });
      }
    });
}
// 拍照点获取坐标
function getCord(state) {
  if (state) {
    $q.dialog({
      dark: ui.isDark,
      title: "获取坐标系",
      message: "是否要立即获取坐标系？",
      html: true,
      cancel: t("cancel"),
    }).onOk(() => {
      getRecognize();
    });
  } else {
    getRecognize();
  }
}
function getRecognize() {
  api
    .post(
      useAPIStore().amrUrl + "ros/call",
      {},
      { params: { service: "/recognize" } }
    )
    .then((res) => {
      if (res.data.values.flag !== 1) {
        $q.dialog({
          dark: ui.isDark,
          title: t(lang + "校准点坐标获取失败"),
          message: t(lang + "检查机械臂摄像头是否对齐拍照点"),
          html: true,
          cancel: t("cancel"),
          ok: t(lang + "重试"),
        })
          .onOk(() => {
            getCord(false);
          })
          .onCancel(() => {});
      } else {
        $q.notify({
          type: "positive",
          message: t(lang + "坐标获取成功"),
        });
      }
    })
    .catch(() => {
      $q.notify({
        type: "negative",
        message: t(lang + "获取坐标异常"),
      });
    });
}

// 获取当前姿态
function getPosture(state, sourceFrame) {
  loading.value = state;
  // 获取当前姿态点信息
  api
    .post(
      useAPIStore().amrUrl + "ros/call",
      {
        target_frame: "flange",
        source_frame: state ? "platform" : sourceFrame,
      },
      { params: { service: "tf/get_frame_pose" } }
    )
    .then((res) => {
      const pose = res.data.values.pose;
      posture.value.child = sourceFrame;
      posture.value.parent = "flange";
      posture.value.pose.orientation.w = pose.pose.orientation.w;
      posture.value.pose.orientation.x = pose.pose.orientation.x;
      posture.value.pose.orientation.y = pose.pose.orientation.y;
      posture.value.pose.orientation.z = pose.pose.orientation.z;
      posture.value.pose.position.x = pose.pose.position.x;
      posture.value.pose.position.y = pose.pose.position.y;
      posture.value.pose.position.z = pose.pose.position.z;
      if (sourceFrame === "flange") {
        leftPosture.value = JSON.parse(JSON.stringify(posture.value));
      } else {
        rightPosture.value = JSON.parse(JSON.stringify(posture.value));
      }

      // 关闭loading
      loading.value = false;
    })
    .catch(() => {
      $q.notify({
        type: "negative",
        message: state
          ? t("routeManage.PosturePoint.获取当前姿态失败请稍后添加")
          : "获取当前夹具坐标失败",
      });
      loading.value = false;
      if (state) {
        $q.dialog({
          dark: ui.isDark,
          title: t("routeManage.PosturePoint.获取姿态失败请检查机械臂是否正常"),
          ok: t("know"),
          cancel: false,
        });
      }
    });
}
// 保存数据
function save(mode) {
  if (mode === "left") {
    api
      .post(useAPIStore().amrUrl + "ros/call", leftPosture.value, {
        params: { service: "/tf/commit_tf" },
      })
      .then((res) => {
        if (res.data.values.success) {
          $q.notify({
            type: "positive",
            message: "左夹具保存成功,请重启OS生效！",
          });
        } else {
          $q.notify({
            type: "negative",
            message: "左夹具保存失败",
          });
        }
      })
      .catch(() => {
        $q.notify({
          type: "negative",
          message: "接口请求异常",
        });
      });
  } else {
    api
      .post(useAPIStore().amrUrl + "ros/call", rightPosture.value, {
        params: { service: "/tf/commit_tf" },
      })
      .then((res) => {
        if (res.data.values.success) {
          $q.notify({
            type: "positive",
            message: "右夹具保存成功,请重启OS生效！",
          });
        } else {
          $q.notify({
            type: "negative",
            message: "右夹具保存失败",
          });
        }
      })
      .catch(() => {
        $q.notify({
          type: "negative",
          message: "接口请求异常",
        });
      });
  }
}

/**
 * 相机预览
 */
async function handleCameraPreview() {
  isPreview.value = true;
  try {
    const response = await api.post(
      useAPIStore().amrUrl + "ros/call",
      {},
      { params: { service: "/raw" } }
    );
    if (response.data.values.flag === 1) {
      getImg();
      isPreview.value = false;
    } else {
      isPreview.value = false;
    }
  } catch (e) {
    isPreview.value = false;
  }
}
// 获取拍照信息
function getImg() {
  const uuid = uuidv4();
  imgRef.value.src = `${
    useAPIStore().rosImgUrl
  }snapshot?topic=/raw_img&quality=50&rad=${uuid}`;
}
</script>
<style scoped></style>
